package com.study.transienttest;

import java.io.*;

/**
 * 序列化测试 被transient修饰的字段不能序列化
 *
 * transient 关键字总结
 *
 * 1）transient修饰的变量不能被序列化；
 *
 * 2）transient只作用于实现 Serializable 接口；
 *
 * 3）transient只能用来修饰普通成员变量字段；
 *
 * 4）不管有没有 transient 修饰，静态变量都不能被序列化；
 */
public class TransientTest {
    public static void main(String[] args) {
        User user=new User();
        user.setId("javs");
        user.setName("JAVA菜鸟！！！");

        System.out.println("\n序列化之前");

        System.out.println("name:"+user.getName()+";;;id:"+user.getId());

        ObjectOutputStream os = null;
        try {
            os = new ObjectOutputStream(new FileOutputStream("d:/user.txt"));
            os.writeObject(user);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        ObjectInputStream is = null;
        try {
            is = new ObjectInputStream(new FileInputStream("d:/user.txt"));
            try {
                user = (User) is.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("\n序列化之后");
        System.out.println("username: " + user.getName());
        System.out.println("id: " + user.getId());
    }
}
